package core

import (
	"github.com/golang-jwt/jwt"
)

type CustomClaims struct {
	jwt.StandardClaims
	User string `json:"user"`
}

func CreateToken(customClaims *CustomClaims, salt string) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, customClaims)
	ss, err := token.SignedString([]byte(Config.Application.Salt + salt))
	if err != nil {
		return "", err
	}
	return ss, nil
}

func ParseToken(tokenString string, salt string) (*CustomClaims, bool) {
	token, err := jwt.ParseWithClaims(
		tokenString,
		&CustomClaims{},
		func(token *jwt.Token) (interface{}, error) { return []byte(Config.Application.Salt + salt), nil },
	)
	if err != nil {
		return nil, false
	}
	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
		return claims, ok
	}
	return nil, false
}
